package com.pyp.kuaishou.repository;

import com.pyp.kuaishou.model.Material;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 作者: lauJinyu
 * 素材数据访问层
 */
@Repository
public class MaterialRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据 app_id 查询符合条件的素材（随机取一条）
     * 条件：is_public=1 且 applicable_platforms 包含指定平台
     */
    public Material findLatestByAppId(String appId) {
        String sql = "SELECT * FROM materials WHERE app_id = ? AND is_public = 1 " +
                    "AND JSON_CONTAINS(applicable_platforms, '\"kuaishou\"') " +
                    "ORDER BY RAND() LIMIT 1";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Material.class), appId);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据 app_id 和 store_id 查询符合条件的素材（随机取一条）
     * 条件：is_public=1 且 applicable_platforms 包含指定平台 且 store_id 匹配
     * 作者: lauJinyu
     */
    public Material findLatestByAppIdAndStoreId(String appId, String storeId) {
        String sql = "SELECT * FROM materials WHERE app_id = ? AND store_id = ? AND is_public = 1 " +
                    "AND JSON_CONTAINS(applicable_platforms, '\"kuaishou\"') " +
                    "ORDER BY RAND() LIMIT 1";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Material.class), appId, storeId);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 更新素材使用统计
     * @param materialId 素材ID
     */
    public void updateMaterialUsage(Long materialId) {
        String sql = "UPDATE materials SET use_count = COALESCE(use_count, 0) + 1, " +
                    "last_used_at = ? WHERE id = ?";
        jdbcTemplate.update(sql, LocalDateTime.now(), materialId);
    }
}